package syferserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

/**
 *
 * @author Yannick
 */
public class Channel extends Thread {

    private int port;
    private static int voicePort = 55555;
    private static int msgsPort = 55556;
    public Vector<CommunicationHandler> communications = new Vector<CommunicationHandler>();
    private Work work;
    UDPStream udp;

    public Channel(int port) {
        this.port = port;
    }

    public int getPort(){
        return this.port;
    }

    public void run() {
        try {
            ServerSocket msgs = new ServerSocket(msgsPort);
            Socket socket = null;
            udp = new UDPStream(port,true);

            work = new Work();
            work.start();


            while (true) {
                socket = msgs.accept();

                System.out.println("New client connected: " + socket.getRemoteSocketAddress());

                CommunicationHandler user = new CommunicationHandler(socket,this);
                user.start();
            }
        } catch (IOException ex) {
        }

    }

    public class Work extends Thread {

        public void run() {
            byte tempBuffer[] = new byte[1024];
            while (udp.r.read(tempBuffer)) {
                synchronized (communications) {
                    for (Iterator<CommunicationHandler> it = communications.iterator(); it.hasNext();) {
                        CommunicationHandler temp = it.next();

                        if(!(temp.udp.ipa.equals( udp.rip )&& temp.udp.uitport ==udp.rport))
                            temp.udp.w.write(tempBuffer);
                    }
                }

            }
        }
    }
}
